package com.coder520.mamabike.security;

/**
 * Created by ASUS on 2017/8/14.
 */

import com.coder520.mamabike.bo.UserBo;
import com.coder520.mamabike.common.Const;
import com.coder520.mamabike.common.exception.GrantedAuthorityException;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;

/**身份验证提供者*/
public class MyAuthenticationProvider implements AuthenticationProvider {

    @Override
    /**认证*/
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if(authentication instanceof PreAuthenticatedAuthenticationToken){
            PreAuthenticatedAuthenticationToken authenticationToken = (PreAuthenticatedAuthenticationToken) authentication;
            MyAuthenticationToken myAuthenticationToken = (MyAuthenticationToken) authenticationToken.getPrincipal();
            if(CollectionUtils.isNotEmpty(myAuthenticationToken.getAuthorities())){
                /**获取权限信息*/
                GrantedAuthority authority = myAuthenticationToken.getAuthorities().iterator().next();
                if(Const.Role.BIEK_CLIENT.equals(authority.getAuthority())){
                    return myAuthenticationToken;
                }else if (Const.Role.ROLE_SOME.equals(authority.getAuthority())){
                    return myAuthenticationToken;
                }
            }
        }else if (authentication instanceof MyAuthenticationToken){
            MyAuthenticationToken myAuthenticationToken = (MyAuthenticationToken) authentication;
            if(CollectionUtils.isNotEmpty(myAuthenticationToken.getAuthorities())){
                /**获取权限信息*/
                GrantedAuthority authority = myAuthenticationToken.getAuthorities().iterator().next();
                if(Const.Role.BIEK_CLIENT.equals(authority.getAuthority())){
                    return myAuthenticationToken;
                }else if (Const.Role.ROLE_SOME.equals(authority.getAuthority())){
                    return myAuthenticationToken;
                }
            }
        }
        throw new GrantedAuthorityException("unknow error");
    }

    @Override
    /**是否支持类型*/
    public boolean supports(Class<?> aClass) {
        return PreAuthenticatedAuthenticationToken.class.isAssignableFrom(aClass)||MyAuthenticationToken.class.isAssignableFrom(aClass);
    }
}
